package com.csust.cg.mongodb.service.impl;

import com.csust.cg.mongodb.domain.HttpStatus;
import com.csust.cg.mongodb.domain.Result;
import com.csust.cg.mongodb.domain.entity.User;
import com.csust.cg.mongodb.mapper.UserMapper;
import com.csust.cg.mongodb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @author chenguang
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User checkUser(String username, String password) {
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        return userMapper.selectUserByUsernameAndPassword(username, password);
    }

    @Override
    public Result createUser(String username, String password) {
        User user;
        try {
            user = userMapper.selectUserByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请联系开发人员！");
        }
        if (user != null) {
            return new Result(HttpStatus.USER_ALREADY_EXISTS, "用户已存在！");
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setUsername(username);
        user.setPassword(password);
        user.setCreateTime(new Date());
        Integer line;
        try {
            line = userMapper.createUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请联系开发人员！");
        }
        if (line > 0) {
            return Result.success();
        } else {
            return Result.error("系统创建用户出错！");
        }
    }

    @Override
    public User selectUserById(String id) {
        return userMapper.selectUserById(id);
    }
}
